using UnityEngine;
using System.Collections;

public class TransitionOnButtonEvent : CharacterAction
{
	public bool conditionCounter = false;
	public enum ButtonEventType
	{
		OnButtonUp,
		OnButtonDown
	}
	public ButtonEventType eventType = ButtonEventType.OnButtonUp;
	public ButtonType buttonType;
	public CharacterAnimatedState toState;
	public int actionFrame;

    public bool activated;

	public override void OnActionEnter (Character character)
	{
		base.OnActionEnter(character);

		activated = false;

		if(eventType == ButtonEventType.OnButtonDown)
			character.onButtonCommand.OnEvent += OnButtonCommand;
		if(eventType == ButtonEventType.OnButtonUp)
			character.onButtonCommandEnd.OnEvent += OnButtonCommandEnd;
	}

	public override void OnActionExit (Character character)
	{
		base.OnActionExit(character);
		if(eventType == ButtonEventType.OnButtonDown)
			character.onButtonCommand.OnEvent -= OnButtonCommand;
		if(eventType == ButtonEventType.OnButtonUp)
			character.onButtonCommandEnd.OnEvent -= OnButtonCommandEnd;
		activated = false;
	}
	
	public void OnButtonCommand(Character.ButtonCommand arg)
	{
		if(MatchCondition() == false)
			return;

		if(buttonType == arg.button)
		{
			activated = true;
		}
	}
	
	public void OnButtonCommandEnd(Character.ButtonCommandEnd arg)
	{
		if(MatchCondition() == false)
			return;

		if(buttonType == arg.button)
		{
			activated = true; 
		}
	}

	public override void OnFrameUpdate (Character.FrameUpdate arg)
	{
		if(activated == true && arg.character.curFrame >= actionFrame)
		{
			activated = false;
			arg.character.ToState(toState.stateName);
		}
	}

	public bool MatchCondition()
	{
		if(conditionCounter && character.counterCharacters.Count == 0)
		{
            Debug.LogError("character.counterCharacters.count=" + character.counterCharacters.Count);
			return false;
		}

		return true;
	}
}

